package cn.leonis.newcoder;

import cn.leonis.leetcode.ListNode;

/**
 * @Author Tobi
 * @Date 2021-06-21 上午1:12
 * 反转链表
 */
public class ReverseListSolution {

    public static void main(String[] args) {
        // Init Data
        ListNode head = new ListNode(1);
        ListNode node2 = new ListNode(2);
        head.next = node2;
        ListNode node3 = new ListNode(3);
        node2.next = node3;
        ListNode node4 = new ListNode(4);
        node3.next = node4;
        ListNode node5 = new ListNode(5);
        node4.next = node5;

        ReverseListSolution solution = new ReverseListSolution();

        System.out.println(solution.reverseListNode(head));

    }

    public ListNode reverseListNode(ListNode head) {
        if (head == null) {
            return null;
        }

        if (head.next == null) {
            return head;
        }

        ListNode preNode = null;
        ListNode nextNode = null;
        ListNode currentNode = head;

        while (currentNode != null) {
            nextNode = currentNode.next;
            currentNode.next = preNode;
            preNode = currentNode;
            currentNode = nextNode;
        }

        return preNode;

    }
}
